from __future__ import absolute_import
import os
#import os.path
#import glob
#import logging
#import shutil
from os.path import join, isfile, split #, isdir, exists
from forest.registry import register_tool
#from forest.tool import Tool

@register_tool('system.which')
def which(program):
    def is_exe(fpath):

        return isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = split(program)
    if fpath:
        if is_exe(program):
            return program
    else:

        paths = os.environ["PATH"]

        paths = '{}'.format(os.pathsep).join(['/bin', '/sbin', '/usr/bin', '/usr/sbin'])

        for path in paths.split(os.pathsep):

            exe_file = join(path, fname)
            if is_exe(exe_file):
                return exe_file

    return None

@register_tool('require_exec')
def require_executable(name):
    path = which(name)

    if path is None:
        raise Exception("Forest requires the executable '%s'. Please make sure it is installed." % name)
    return path
